<?php
/**
 * 获取所有分类
 * User: yuanxuncheng
 * File: GetGoods.php
 * Date: 2017/1/2
 * Time: 23:13
 */

namespace app\api\model\page\goods;

use app\api\model\dao\GoodsCategory;
use app\library\Error;
use app\library\PageBase;
use think\Validate;
use think\Cache;
use app\library\RedisMgr;

class GetGoodsCategory extends PageBase
{

    private $objRedis;
    private $redisPre;
    private $objGoodsCategory;

    public function __construct()
    {
        parent::__construct();
        $this->objRedis = RedisMgr::getInstance([]);
        $this->redisPre = 'MS:GOODSCATEGORY:ALL';
        $this->objGoodsCategory = new GoodsCategory();
    }

    public function excute($param)
    {
        // 先从REDIS中取
        $ret = $this->objRedis->get($this->redisPre);
        if ($ret) {
            $this->data = $ret;
        }

        $return = array();

        $rets = $this->objGoodsCategory->getAllGoodsCategory();

        if (false === $rets) {
            return $this->getRes(Error::ERR_SYS);
        }
        if ($rets) {
            foreach ($rets as $item) {
                if (isset($item['parent_id']) && $item['parent_id'] == 0) {
                    $return[$item['cat_id']]['parent_cat'] = $item;
                } else {
                    $return[$item['parent_id']]['sub_cat'][] = $item;
                }
            }

            $rets = array_values($return);
            $return = array();
            foreach ($rets as $ret) {
                if (isset($ret['parent_cat'])) {
                    $parent = $ret['parent_cat'];
                }
                $parent['sub_cat'] = '';
                if (isset($ret['sub_cat'])) {
                    $subs = $ret['sub_cat'];
                    foreach ($subs as $sub) {
                        $parent['sub_cat'] .= $sub['cat_name'];
                    }
                }
                $return[] = $parent;
            }
        }


        $this->data = $return;
        return $this->getRes();
    }
}
